1
//--------------------------------------------------------------------------
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 // File: ObservableConcurrentCollection.cs
7 //--------------------------------------------------------------------------
9 using System
.Collections
.Specialized
;
10 using System
.ComponentModel
;
11 using System
.Threading
;
12 using System
.Diagnostics
;
14 namespace System
.Collections
.Concurrent
17 /// Provides a thread-safe, concurrent collection for use with data binding.
19 /// <typeparam name="T">Specifies the type of the elements in this collection.</typeparam>
20 [DebuggerDisplay("Count={Count}")]
21 [DebuggerTypeProxy(typeof(IProducerConsumerCollection_DebugView
<>))]
22 public class ObservableConcurrentCollection
<T
> :
23 ProducerConsumerCollectionBase
<T
>, INotifyCollectionChanged
, INotifyPropertyChanged
25 private readonly SynchronizationContext _context
;
28 /// Initializes an instance of the ObservableConcurrentCollection class with an underlying
29 /// queue data structure.
31 public ObservableConcurrentCollection() : this(new ConcurrentQueue
<T
>()) { }
34 /// Initializes an instance of the ObservableConcurrentCollection class with the specified
35 /// collection as the underlying data structure.
37 public ObservableConcurrentCollection(IProducerConsumerCollection
<T
> collection
) : base(collection
)
39 _context
= AsyncOperationManager
.SynchronizationContext
;
42 /// <summary>Event raised when the collection changes.</summary>
43 public event NotifyCollectionChangedEventHandler CollectionChanged
;
44 /// <summary>Event raised when a property on the collection changes.</summary>
45 public event PropertyChangedEventHandler PropertyChanged
;
48 /// Notifies observers of CollectionChanged or PropertyChanged of an update to the dictionary.
50 private void NotifyObserversOfChange()
52 var collectionHandler
= CollectionChanged
;
53 var propertyHandler
= PropertyChanged
;
54 if (collectionHandler
!= null || propertyHandler
!= null)
58 if (collectionHandler
!= null)
60 collectionHandler(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction
.Reset
));
62 if (propertyHandler
!= null)
64 propertyHandler(this, new PropertyChangedEventArgs("Count"));
70 protected override bool TryAdd(T item
)
72 // Try to add the item to the underlying collection. If we were able to,
73 // notify any listeners.
74 bool result
= base.TryAdd(item
);
75 if (result
) NotifyObserversOfChange();
80 protected override bool TryTake(out T item
)
82 // Try to remove an item from the underlying collection. If we were able to,
83 // notify any listeners.
84 bool result
= base.TryTake(out item
);
85 if (result
) NotifyObserversOfChange();